<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Category extends Controller
{
    protected $middleware = [
        'CheckAdmin'
    ];

    public function lists(Request $request)
    {
        if ($request->isAjax()) {
            $list = Db('category')->order('sort asc')->select();
            return ['code' => 0, 'data' => $list];
        } else {
            return $this->fetch();
        }
    }

    public function add(Request $request)
    {
        if ($request->isPost()) {
            $data = [];
            $data['name'] = $request->post('name', '', 'trim');
            $data['sort'] = $request->post('sort', 99, 'intval');
            if ($data['name'] == '') {
                return ['code' => 1, 'msg' => '请填写分类名字'];
            }
            if (false === Db('category')->insert($data)) {
                return ['code' => 1, 'msg' => '操作失败'];
            } else {
                return ['code' => 0, 'msg' => '操作成功'];
            }
        } else {
            return $this->fetch();
        }
    }

    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $data = [];
            $category_id = $request->post('category_id', 0, 'intval');
            $data['name'] = $request->post('name', '', 'trim');
            $data['sort'] = $request->post('sort', 99, 'intval');
            if ($data['name'] == '') {
                return ['code' => 1, 'msg' => '请填写分类名字'];
            }
            if (false === Db('category')->where('category_id', $category_id)->update($data)) {
                return ['code' => 1, 'msg' => '操作失败'];
            } else {
                return ['code' => 0, 'msg' => '操作成功'];
            }
        } else {
            $category_id = $request->get('id', 0, 'intval');
            $info = Db('category')->where('category_id', $category_id)->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }
}